import { Form, Input, Modal, Spin } from 'antd';

import React, { useEffect, useState } from 'react';
import type { SysDictItem, SysDictItemUpdate } from '@/pages/System/DictCode/data';
import TextArea from 'antd/lib/input/TextArea';

interface EditFormProps {
  // 规则的唯一id
  dictId: string;
  // 请求修改数据的回调
  onSubmit: (values: SysDictItemUpdate) => void;
  // 取消窗口的回调
  onCancel: (flag?: boolean) => void;
  // 窗口是否可见
  modalVisible: boolean;
  // 获取规则详情的请求
  request: (sysDict: string) => Promise<{ success: boolean; data: SysDictItem | null }>;
}

const formItemLayout = {
  labelCol: {
    xs: { span: 4 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 20 },
    sm: { span: 20 },
  },
};

const EditForm: React.FC<EditFormProps> = (props) => {
  const [form] = Form.useForm();
  const [loadingRequest, setLoadingRequest] = useState<boolean>(false);
  const [sysDict, setSysDict] = useState<SysDictItemUpdate>({
    id: '',
    dataDesc: '',
    dataValue: '',
  });

  const {
    dictId,
    onSubmit: handleEdit,
    onCancel: handleEditModalVisible,
    modalVisible: editModalVisible,
  } = props;

  useEffect(() => {
    if (!dictId) throw new Error('dictId 不能为空');
    setLoadingRequest(true);

    props
      .request(dictId)
      .then((res) => {
        if (res.success && res.data !== null) {
          setSysDict(res.data);
          form.setFieldsValue(res.data);
        }
      })
      .finally(() => {
        setLoadingRequest(false);
      });
  }, ['dictId']);

  const onModalOk = async () => {
    const fieldsValue = await form.validateFields();
    const dictItem: SysDictItemUpdate = { ...fieldsValue, ...sysDict, id: dictId };
    handleEdit(dictItem);
  };

  return (
    <Modal
      title="修改字典值"
      visible={editModalVisible}
      destroyOnClose
      onOk={() => onModalOk()}
      onCancel={() => handleEditModalVisible(false)}
      afterClose={() => handleEditModalVisible()}
      okText="确定"
      cancelText="取消"
    >
      <Spin spinning={loadingRequest}>
        <Form {...formItemLayout} form={form}>
          <Form.Item name="dataCode" label="字典编码" rules={[{ required: true, message: '必填' }]}>
            <Input disabled />
          </Form.Item>

          <Form.Item name="dataValue" label="字典值" rules={[{ required: false, message: '选填' }]}>
            <Input
              onChange={(value) => setSysDict({ ...sysDict, dataValue: value.target.value })}
            />
          </Form.Item>

          <Form.Item
            name="dataDesc"
            label="字典说明"
            rules={[{ required: false, message: '选填' }]}
          >
            <TextArea
              onChange={(value) =>
                setSysDict({
                  ...sysDict,
                  dataDesc: value.target.value,
                })
              }
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
};
export default EditForm;
